package com.cocolover2.andbase.caches;

import android.graphics.Bitmap;
import android.util.LruCache;

/**
 * 内存缓存(measured in bytes 单位:字节)
 * 1.支持字符串
 * 2.支持bitmap
 * Created by cocolove2 on 17/8/15.
 */

class MemoryCacheImpl implements CocoCaches {
    private LruCache<String, Object> mLruCache;

    public MemoryCacheImpl() {
        initLruCache();
    }

    private void initLruCache() {
        if (mLruCache == null) {
            long size = Runtime.getRuntime().maxMemory();
            mLruCache = new LruCache<String, Object>((int) (size / 8)) {
                @Override
                protected int sizeOf(String key, Object value) {
                    int size = 0;
                    if (value instanceof Bitmap) {
                        size = ((Bitmap) value).getByteCount();
                    } else if (value instanceof String) {
                        size = ((String) value).getBytes().length;
                    } else {
                        size = super.sizeOf(key, value);
                    }
                    return size;
                }
            };
        }
    }

    @Override
    public void saveToCache(String key, Object value) {
        if (value instanceof Bitmap || value instanceof String) {
            initLruCache();
            mLruCache.put(key, value);
        } else {
            throw new UnsupportedOperationException("当前不支持 bitmap和String 以外的对象存储");
        }
    }

    @Override
    public Object getFromCache(String key, Object defaultObject) {
        initLruCache();
        Object object = mLruCache.get(key);
        if (object == null) {
            object = defaultObject;
        }
        return object;
    }

    @Override
    public void removeFromCache(String key) {
        initLruCache();
        mLruCache.remove(key);
    }

    @Override
    public void clearCache() {
        initLruCache();
        mLruCache.evictAll();
    }
}
